import pymysql
# 封装操作数据库
class DButils:
    def __init__(self, host='localhost', user='root', password='root', database='finance', port=3306,charset='utf8'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.port = port
        self.charset = charset

    def update(self, sql, params=None):
        try:
            db = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset=self.charset
            )
            cursor = db.cursor()
            cursor.execute(sql, params)
            db.commit()
            print('数据操作成功',end=' ')
        except Exception as e:
            print('数据操作失败',end=' ')
            print(sql)
            print(e)

    def select(self, sql, params=None):
        try:
            db = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database,
                port=self.port,
                charset=self.charset
            )
            cursor = db.cursor()
            cursor.execute(sql, params)
            result = cursor.fetchall()
            return result
        except Exception as e:
            print('数据查询失败',end=' ')
            print(sql)
            print(e)

if __name__ == '__main__':
    d = DButils('localhost', 'root', 'root', 'test_db')
    sql = 'select * from Sans'
    result = d.select(sql)
    print(result)
    sql_drop='drop table if exists Sans'
    d.update(sql_drop)











